package com.gameapplet.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gameapplet.cash.model.Balance;
import com.gameapplet.cash.service.Impl.BalanceServiceImpl;
import com.gameapplet.user.model.User;
import com.gameapplet.user.service.Impl.UserServiceImpl;
import com.gameapplet.util.AESUtil;
import com.gameapplet.util.Base64Util;
import java.util.Map;

import com.gameapplet.util.GetUUID;
import com.gameapplet.util.HttpTookit;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    final static String AppID = "wx600ff0c7239c70f1";
    final static String Secret = "4cc8787904427e3da046a71c420d57d8";
    @Resource(name = "userService")
    private UserServiceImpl userService;
    @Resource(name = "balanceService")
    private BalanceServiceImpl balanceService;

    @RequestMapping(value = "/getWxUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public User getUserInfo(@RequestBody Map map) throws java.lang.Exception {
        // 被加密的数据;
        //code  生命周期五分钟。只能访问一次
        String JsCode = map.get("code").toString();
        //用code获取sessionkey和openid的官方接口
        String requestUrl = ("https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=J" +
                "SCODE&grant_type=authorization_code").replace("APPID", AppID).replace("SECRET",
                Secret).replace("JSCODE", JsCode);  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        //工具类 模拟请求
        String openIdResult = HttpTookit.doGet(requestUrl, null);
        JSONObject openIdResultJson = JSONObject.parseObject(openIdResult);


        String sessionKey = openIdResultJson.getString("session_key");
        String openid = openIdResultJson.getString("openid");
        String encryptedData = map.get("encryptedData").toString();
        String iv = map.get("iv").toString();
        try {
            //解密工具类 传入encryptedData,sessionKey,iv
            byte[] resultByte = AESUtil.instance.decrypt(encryptedData, sessionKey, iv);
            if (null != resultByte && resultByte.length > 0) {
                //UTF-8格式
                String result = new String(resultByte, "UTF-8");
                JSONObject UserInfoResultJson = JSONObject.parseObject(result);
                System.out.println("UserInfoResultJson---------------------------" + UserInfoResultJson);

                //以下建议保留
                // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
//        int base = 16;
//        if (keyByte.length % base != 0) {
//            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
//            byte[] temp = new byte[groups * base];
//            Arrays.fill(temp, (byte) 0);
//            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
//            keyByte = temp;
//        }
//        // 初始化
//        Security.addProvider(new BouncyCastleProvider());
//        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
//        parameters.init(new IvParameterSpec(ivByte));
//        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//        byte[] resultByte = cipher.doFinal(dataByte);
//        if (null != resultByte && resultByte.length > 0) {
//            String result = new String(resultByte, "UTF-8");
//            JSONObject UserInfoResultJson = JSONObject.parseObject(result);
//            System.out.println("UserInfoResultJson---------------------------"+UserInfoResultJson);

                User user = new User();
                if (userService.getUserById(UserInfoResultJson.getString("openId")) == null ? true : false) {//判断是否新用户
                    user.setOpenid(UserInfoResultJson.getString("openId"));
                    user.setNickname(UserInfoResultJson.getString("nickName"));
                    user.setHeadURL(UserInfoResultJson.getString("avatarUrl"));
                    user.setSex(UserInfoResultJson.getInteger("gender"));
                    user.setCountry(UserInfoResultJson.getString("country"));
                    user.setProvince(UserInfoResultJson.getString("province"));
                    user.setCity(UserInfoResultJson.getString("city"));
                    user.setCurrentstage(0);
                    user.setMaxstage(userService.selectMaxStage());
                    userService.insertUser(user);
                    Balance balance = new Balance();
                    balance.setBalanceid(GetUUID.getUUID());
                    balance.setOpenid(UserInfoResultJson.getString("openId"));
                    balance.setBalance(0.00);
                    balanceService.insertBalance(balance);

                } else{
                    String username = UserInfoResultJson.getString("nickName");
                    String headURL = UserInfoResultJson.getString("avatarUrl");
                    user = userService.getUserById(UserInfoResultJson.getString("openId"));

                    user.setMaxstage(userService.selectMaxStage());

                    if (!username.equals(user.getNickname())) {
                        user.setNickname(username);
                        userService.updateUser(user);
                    }
                    if (!headURL.equals(user.getHeadURL())) {
                        user.setHeadURL(headURL);
                        userService.updateUser(user);
                    }
                }
               int i =  user.getCurrentstage();
                return user;
            }
//    } catch (NoSuchAlgorithmException e){
//        e.printStackTrace();
//        //
//    } catch (NoSuchPaddingException e) {
//        e.printStackTrace();
//        //
//    } catch (InvalidParameterSpecException e) {
//        e.printStackTrace();
//        //
//    } catch (IllegalBlockSizeException e) {
//        e.printStackTrace();
//        //
//    } catch (BadPaddingException e) {
//        e.printStackTrace();
//        //
//    } catch (UnsupportedEncodingException e) {
//        e.printStackTrace();
////            log.error(e.getMessage(), e);
//    } catch (InvalidKeyException e) {
//        e.printStackTrace();
//            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
//            log.error(e.getMessage(), e);
//    } catch (NoSuchProviderException e) {
//        e.printStackTrace();
//            log.error(e.getMessage(), e);
        }
        return null;
    }
    @RequestMapping(value = "/getWxInfo", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getWxInfo(@RequestBody Map map) throws java.lang.Exception{
        // 被加密的数据;
        //code  生命周期五分钟。只能访问一次
        String JsCode = map.get("code").toString();
        //用code获取sessionkey和openid的官方接口
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code".replace("APPID", AppID).replace("SECRET", Secret).replace("JSCODE", JsCode);  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        //工具类 模拟请求
        String openIdResult = HttpTookit.doGet(requestUrl, null);

        JSONObject openIdResultJson = JSONObject.parseObject(openIdResult);


        String sessionKey = openIdResultJson.getString("session_key");
        String openid = openIdResultJson.getString("openid");
        String encryptedData = map.get("encryptedData").toString();
        String iv = map.get("iv").toString();
            //解密工具类 传入encryptedData,sessionKey,iv
            byte[] resultByte = AESUtil.instance.decrypt(encryptedData, sessionKey, iv);
            if (null != resultByte && resultByte.length > 0) {
                //UTF-8格式
                String result = new String(resultByte, "UTF-8");
                JSONObject WxInfoResultJson = JSONObject.parseObject(result);
                System.out.println("WxInfoResultJson---------------------------" + WxInfoResultJson);
                return WxInfoResultJson;
            }
        return null;
    }
    @RequestMapping("/groupInfo")
    @ResponseBody
    public  String  savegroup(@RequestBody Map map){//分享一次保存一下opengid 和openid 造成查询群排行榜的时候笛卡尔积
        //每个群ID只对应一次openid 不能重复
        String opengid = map.get("openGid").toString();
        String openid = map.get("openId").toString();
        if(userService.selectGroupById(opengid,openid)==null){
            userService.insertGroup(opengid,openid);
            String message = "保存成功";
            return message;
        }
        return "本群已有此用户";
    }
}
